<template>
	<view class="animation-fade">
		<uni-nav-bar :fixed="true" @clickLeft="handleBack" :title="TabCur == 1 ? '向岛上有家书店租书':'向岛上有家书店买书'" leftIcon="back" :statusBar="true"></uni-nav-bar>

		<scroll-view class="bg-white nav text-center fixed" style="top: 60px;">
			<view class="cu-item text-lg" :class="index==TabCur?'text-yellow cur':''" v-for="(item,index) in cartNames" :key="index" @tap="tabSelect" :data-id="index">
				{{item}}
			</view>
		</scroll-view>
		<view class="box" style="margin-top: 40px;">
			<!-- 买书部分 -->
			<myCart ref="buyCart" v-if="TabCur==0" @deleteBook="deleteItem" @cartChange="handleBuyCartChange" :cartBooks="buyBooks" ></myCart>
			<!-- 租书部分 -->
			<myCart ref="rentCart" v-if="TabCur==1" @deleteBook="deleteItem" @cartChange="handleRentCartChange" :cartBooks="rentBooks" ></myCart>

			<view class="myfoot">
				<view class="" style="height:450rpx;"></view>	
				<view class="">
					<!-- <view class="bg-blue" style="height:550rpx; width: 100%;"></view> -->
					<view style="z-index: 9; " class="foot flex cu-bar flex-direction bg-white solids">
						<view class="">
							<view class="cu-bar btn-group padding-sm  flex flex-direction">
								<view class="">
									<button @click="handleScan" class="cu-btn bg-yellow shadow-blur round lg button-hover text-white">
										<text class="cuIcon-scan lg margin-right-sm"></text>
										扫码{{TabCur == 1?'租书':'买书'}}</button>
									<button @click="show()" class=" cu-btn bg-white shadow shadow-lg round lg button-hover text-black">
										<text class="cuIcon-write lg margin-right-sm"></text>
										手动输入
									</button>
								</view>
							</view>
			
							<view class="margin-bottom search padding-right-xl padding-left-xl" v-if="show_input">
								<view class="search-form round text-grey text-xs text-left">
			
									<input maxlength="13" type="number" @input="handleInput" style="width: 450rpx;" class="padding-left" placeholder="请手动输入ISBN"
									 placeholder-class="text-sm text-grey"></input>
									<button @click="handleSearch" class=" cu-btn round solids" style="background-color: #E7E7E7;margin: 0;">
										<text class="cuIcon-search"></text>
									</button>
								</view>
							</view>
			
			
			
						</view>
			
			
						<view class="">
							<view style="width: 100vw;" class="flex  cu-bar padding bg-gray">
								<view class="flex-twice ">
									<view class="flex  align-center">
										<checkbox-group>
			
											<checkbox class="yellow round margin-right-sm" :checked="TabCur?totRentChoosed:totBuyChoosed " @click="chooseAll" :disabled="flag"></checkbox>
										</checkbox-group>
										<view class="text-black text-lg">
											已选
											<text>{{TabCur?totRentCount:totBuyCount}}</text>
										</view>
										<view class="text-grey text-lg margin-left-lg margin-right-sm">
											总计
										</view>
										<view class="text-price text-xxl text-blue ">
											{{TabCur?totRentPrice:totBuyPrice}}
										</view>
			
									</view>
			
								</view>
								<view class=" ">
									<button id="nextBtn" @click="handlePay" class="cu-btn bg-yellow text-white lg radius">结算</button>
								</view>
							</view>
						</view>
					</view>
			
				</view>
			</view>
		</view>
		
	</view>


</template>

<script>
	import {handleSearch,handleAddCartItem,queryCart,deleteCartItem,updateCartItems} from '../../request/handleReq.js';
	import {mapState,mapMutations} from 'vuex';
	
	var _self;
	export default {
		computed:mapState(['hasLogin']),
		
		
		data() {
			return {			
				totBuyPrice:0.00,
				totBuyCount:0,
				totBuyChoosed:false,
				
				totRentPrice: 0.00,
				totRentCount: 0,
				totRentChoosed: false,
				
				userId:'',
				// newBook: null,
				// newBookIndex: null,
				hidden: true,
				input: "",
				TabCur: 0,
				scrollLeft:0,
				show_input: false,
				cartNames: ["购物车（买书）","购物车（租书）"],
				buyBooks:[],
				rentBooks:[]
				// buyBooks: [
				// {
				// 	bookImg:"https://ae01.alicdn.com/kf/Hcb469ca8b7134edb82b1bda8d158bf43v.jpg",
				// 	bookName:"大傻",
				// 	author:"老大",
				// 	price:11,
				// 	bookNum:1,
				// 	checked:true
				// },
				// {
				// 	bookImg:"https://ae01.alicdn.com/kf/Hcb469ca8b7134edb82b1bda8d158bf43v.jpg",
				// 	bookName:"大傻",
				// 	author:"老大",
				// 	price:11,
				// 	bookNum:1,
				// 	checked:true
				// },
				// {
				// 	bookImg:"https://ae01.alicdn.com/kf/Hcb469ca8b7134edb82b1bda8d158bf43v.jpg",
				// 	bookName:"二傻",
				// 	author:"老大",
				// 	price:11,
				// 	bookNum:2,
				// 	checked:true
				// },
				// {
				// 	bookImg:"https://ae01.alicdn.com/kf/Hcb469ca8b7134edb82b1bda8d158bf43v.jpg",
				// 	bookName:"三傻",
				// 	author:"老大",
				// 	price:11,
				// 	bookNum:3,
				// 	checked:true
				// }],
				
				// rentBooks: [{
				// 	bookImg:"https://ae01.alicdn.com/kf/Hcb469ca8b7134edb82b1bda8d158bf43v.jpg",
				// 	bookName:"大懒",
				// 	author:"老大",
				// 	price:11,
				// 	bookNum:1,
				// 	checked:true
				// },
				// {
				// 	bookImg:"https://ae01.alicdn.com/kf/Hcb469ca8b7134edb82b1bda8d158bf43v.jpg",
				// 	bookName:"小懒",
				// 	author:"老大",
				// 	price:11,
				// 	bookNum:2,
				// 	checked:true
				// }]
			}
		},
		onLoad(option) {
			
			var _self = this;
			this.TabCur = option.TabCur;
			this.handleQueryCart(option.book?JSON.parse(decodeURIComponent(option.book)):null);
			
						
		},		
		
		onUnload(){
			console.log('unload');
			this.updateCart()
		},
		
		
			
		methods: {
			...mapMutations(['generateCarts']),
			handleQueryCart(newBook){
				// console.log(newBook);
				
				queryCart(0).then(res => {
					if(res.data.code == 200){
						// console.log(res);
						res.data.data.forEach(item => {
							let book = {
								...item.book,
								num:item.num,
								checked:true
							}
							if(this.buyBooks.every(i => {
								return i.isbn != item.book.isbn
							})){
								
								this.buyBooks.push(book);
							}
						})
			
						if(newBook && this.TabCur == 0){
							this.addNewBook(newBook)
						}
						
					}else{
						uni.showModal({
							title:'错误',
							content:res.data.msg,
							mask:true,
							showCancel:false
						});
					}
				}).catch(reason => {
					uni.showModal({
						title:'错误',
						content:reason,
						mask:true,
						showCancel:false
					});
				})
				
				queryCart(1).then(res => {
					// console.log(res);
					if(res.data.code == 200){
						// console.log(res.data.data);
						res.data.data.forEach(item => {
							let book = {
								...item.book,
								num:item.num,
								checked:true
							}
							
							if(this.rentBooks.every(i => {
								return i.isbn != item.book.isbn
							})){
								// console.log('query(1)');
								this.rentBooks.push(book);
							}
						})
						
		
						if(newBook && this.TabCur == 1){
							this.addNewBook(newBook)
						}
						
					}else{
						uni.showModal({
							title:'错误',
							content:res.data.msg,
							mask:true,
							showCancel:false
						});
					}
				}).catch(reason => {
					uni.showModal({
						title:'错误',
						content:reason,
						mask:true,
						showCancel:false
					});
				})
			},
			
			// 子组件修改后传回买书购物车信息（列表，总数，总价，全选）
			handleBuyCartChange(e){
				// console.log('buy');
				// console.log(e);
				this.buyBooks = e.cartBooks;
				this.totBuyChoosed = e.allChoosed;
				this.totBuyPrice = e.totPrice.toFixed(2);
				this.totBuyCount = e.totCount;
				
			},	
			// 子组件修改后传回租书购物车信息（列表，总数，总价，全选）
			handleRentCartChange(e){
				this.rentBooks = e.cartBooks;
				this.totRentChoosed = e.allChoosed;
				this.totRentPrice = e.totPrice.toFixed(2);
				this.totRentCount = e.totCount;
				
			},
			tabSelect(e) {
				// console.log('tab');
				this.TabCur = e.currentTarget.dataset.id;
				// queryCart(this.TabCur).then(res => {
				// 	console.log(res);
				// })
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
			},
			handleBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 全选
			chooseAll(e) {
				// console.log(e);
				if(this.TabCur == 1){
					this.totRentChoosed = !this.totRentChoosed;
					this.rentBooks.forEach(v => v.checked = this.totRentChoosed);
					this.$refs.rentCart.setCart(this.rentBooks);
				}else{
					this.totBuyChoosed = !this.totBuyChoosed;
					this.buyBooks.forEach(v => v.checked = this.totBuyChoosed);
					
					
					this.$refs.buyCart.setCart(this.buyBooks);
				}
				
			},
			// 显示输入框
			show() {
				this.show_input = !this.show_input;
			},
			
			//更新购物车信息
			updateCart(){
				updateCartItems({
					items:this.buyBooks,
					type:0
				})
				
				updateCartItems({
					items:this.rentBooks,
					type:1
				})
			},
			
			// 处理输入框内容,并发起请求
			handleInput(e) {
				this.input = e.detail.value;
				// console.log(_self.input);
			},
			addNewBook(newBook){
				// console.log('add');
				// let newBook = uni.getStorageSync("books")[index];
				newBook['checked'] = true;
				newBook['num'] = 1;
				// let newBookImg = newBook.img;
				// console.log(newBook);
				if(this.TabCur == 1){
					
					if(this.rentBooks.some((item) => {
						return item.isbn == newBook.isbn
					})){
						/* 如果购物车里有该书，则退出*/
						uni.showToast({
													
							title: '已存在该商品项',
							mask: true
						})
						return;
					}
					
					
					handleAddCartItem({
						isbn:newBook.isbn,
						num:newBook.num
					},1);
					
					this.rentBooks.push(newBook);
					// this.$refs.rentCart.setCart(this.rentBooks);		
					
					
				}else{					

						// console.log(this.buyBooks);
						if(this.buyBooks.some((item) => {
							return item.isbn == newBook.isbn
						})){
							/* 如果购物车里有该书，则退出*/
							uni.showToast({
														
								title: '已存在该商品项',
								mask: true
							})
							return;
						}
						
						handleAddCartItem({
							isbn:newBook.isbn,
							num:newBook.num,
						},0);
						
						this.buyBooks.push(newBook);
						
						// console.log(s);
						// this.$refs.buyCart.setCart(this.buyBooks);
				}			
			},
			deleteItem(e) {
				var _self = this;
				uni.showModal({
					cancelColor: 'red',
					confirmColor: "#4CD964",
					title: "确认",
					content: '是否确定删除该记录？',
					success(res) {
						if (res.confirm) {
							if(_self.TabCur == 1){
								deleteCartItem(_self.rentBooks[e].isbn,_self.TabCur);
								_self.rentBooks.splice(e,1);
								_self.$refs.rentCart.setCart(_self.rentBooks);
							}else{
								deleteCartItem(_self.buyBooks[e].isbn,_self.TabCur);
								_self.buyBooks.splice(e,1);
								_self.$refs.buyCart.setCart(_self.buyBooks);
							}
							
							
						}
					}
				})
			},
			async handleSearch(e){
				// 9787030467577
				// 9787544740944
				var _self = this;	
				if(this.hasLogin){
					if (this.input.length > 0) {
						// console.log(this.input);
						const res = await handleSearch(this.input);						
						if(_self.TabCur == 1){
							// 租书购物车添加
							_self.addNewBook(res);
							
							// _self.$refs.rentCart.setCart(this.rentBooks);
						}else{
							// 买书购物车添加
							_self.addNewBook(res);
							// _self.$refs.buyCart.setCart(this.buyBooks);
						}
						_self.show();
					}else{
						uni.showModal({
							title:'提示',
							content:'输入内容不能为空',
							mask:true,
							showCancel:false
						});
					}
				}else{
					uni.reLaunch({
						url:'../login/login',
						success: () => {
							this.forceLogin(true);
						}
					})
				}				
			},
			
			
			// hideModal() {
			// 	this.$refs["showImg"].close();
			// 	this.$refs["showImg_self"].close();
			// },
			handleScan() {	
				var _self = this;	
				if(this.hasLogin){
					uni.scanCode({
						onlyFromCamera: true,
						scanType: ['barCode'],
						success: async (result) => {
							// console.log(result.result);
							const res = await handleSearch(result.result);
							// console.log(index);
							if(_self.TabCur == 1){
								// 租书购物车添加
								_self.addNewBook(res);
								// _self.$refs.rentCart.setCart(this.rentBooks);
							}else{
								// 买书购物车添加
								_self.addNewBook(res);
								// _self.$refs.buyCart.setCart(this.buyBooks);
							}									
						}
					});
				}else{
					uni.reLaunch({
						url:'../login/login'
					})
				}
				
				
			},
			// 按钮结算
			handlePay(){
				if(this.TabCur == 1 && this.rentBooks.length === 0){
					uni.showModal({
						title:'提示',
						content:'租书购物车为空',
						mask:true,
						showCancel:false
					});
					return;
				}else if(this.TabCur == 0 && this.buyBooks.length === 0){
					uni.showModal({
						title:'提示',
						content:'买书购物车为空',
						mask:true,
						showCancel:false
					});
					return;
				}
				if(this.TabCur == 1 && this.totRentCount == 0){
					uni.showModal({
						title:'提示',
						content:'租书购物车未选择任何书本',
						mask:true,
						showCancel:false
					});
					return;
				}else if (this.TabCur == 0 && this.totBuyCount == 0){
					uni.showModal({
						title:'提示',
						content:'买书购物车未选择任何书本',
						mask:true,
						showCancel:false
					});
					return;
				}
				
				this.generateCarts({
					buyBooks:this.buyBooks.filter(item=>item.checked),
					rentBooks:this.rentBooks.filter(item=>item.checked)
				});
				
				this.updateCart();
				
				uni.navigateTo({
					url: "../buyRentPay/buyRentPay"
				});
				
				
				
			},


		},
		
	}
</script>


<style>
	.box {
		position: absolute;
		width: 100%;
	}

	.canui-kong {
		padding-top: 200rpx;
	}

	.canui-kong-icon {
		width: 220rpx;
		height: 220rpx;
		/* line-height: 220rpx; */
		margin: 0 auto;
		border-radius: 50%;
		margin-bottom: 30rpx;
	}

	.canui-kong-icon text {
		font-size: 115rpx;
	}

	.canui-kong .bg-gradual-green {
		margin: 0 auto;
	}

	.cu-list.menu-avatar>.cu-item {
		padding-left: 220rpx;
	}


	.line-blue, .lines-blue {
		color: yellow;
	}

</style>
